import Ayaka from '@/ayaka'
import SpawnController, { getCreeps } from '@/modules/structures/spawn'
import { CreepRoles, SpawnTask } from '@/modules/structures/spawn/types'
import { BodyPartArrayType } from '@/utils/common'
import { quickerWork } from './quicker'
import { getRoleCreeps } from '@/modules/global/clearMemory'

export default class QuickStartManager {
    /**
     * 不可实例化
     */
    protected constructor() {
        throw new Error('QuickStartManager 不可被实例化！')
    }

    /**
     * 执行
     */
    public static run(room: MyRoom) {
        if (room.controller.level > 2) return

        const memory = QuickStartManager.getMemory(room)
        const quickers = QuickStartManager.getQuicker(room, memory.quicker)
        QuickStartManager.spawnQuicker(room, memory.quicker)
        QuickStartManager.initQuickerMemory(quickers)
        quickerWork(quickers, room, memory)
    }

    /**
     * 孵化 quicker
     */
    protected static spawnQuicker(room: MyRoom, quickerNames: string[]) {
        // if (!isInterval(31)) return
        if (quickerNames.length >= 5) return
        if (SpawnController.searchSpawnTaskByRole(room, CreepRoles.quicker).length) return
        if (Object.keys(room.memory.structures?.container || {}).length) return
        // 搬运工存在说明房间已经有稳定的能量来源
        // if (
        //     getRoleCreeps(room.name, CreepRoles.transporter).length ||
        //     SpawnController.searchSpawnTaskByRole(room, CreepRoles.transporter).length
        // ) {
        //     return
        // }

        QuickStartManager.addQuickerSpawnTask(room, quickerNames, [WORK, CARRY, MOVE, MOVE])
    }

    /**
     * 初始化 quicker memory
     */
    protected static initQuickerMemory(quickers: Creep[]) {
        quickers.forEach((quicker) => {
            if (!quicker.memory.data) quicker.memory.data = {}
        })
    }

    /**
     * 获取 quicker
     */
    protected static getQuicker(room: MyRoom, quickerNames: string[]) {
        return getCreeps(room, quickerNames)
    }

    /**
     * 添加 quicker 孵化任务
     */
    protected static addQuickerSpawnTask(room: MyRoom, quickerNames: string[], body: BodyPartArrayType) {
        const spawnTask: SpawnTask = {
            role: CreepRoles.quicker,
            body,
        }

        const creepName = SpawnController.addSpawnTask(room, spawnTask)
        if (!creepName) return

        quickerNames.push(creepName)
    }

    /**
     * 获取 memory
     */
    public static getMemory(room: Room) {
        if (!room.memory.quickStart) {
            room.memory.quickStart = {
                quicker: [],
            }
        }
        return room.memory.quickStart
    }

    /**
     * 清理 memory
     */
    public static clearMemory(room: Room) {
        delete room.memory.quickStart
    }
}

// 三级就清除掉
Ayaka.onRoomLevelChange((room, level) => {
    if (level === 3) QuickStartManager.clearMemory(room)
})
